package com.qf.servlet;

import com.github.pagehelper.PageInfo;
import com.qf.pojo.Profile;
import com.qf.service.ProfileService;
import com.qf.service.ProfileServiceImpl;
import com.qf.utils.StringUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@WebServlet("/profileservlet")
@MultipartConfig(maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*20)
public class ProfileServlet extends BaseServlet{
//首先导入配置文件
    ApplicationContext applicationContext =
            new ClassPathXmlApplicationContext("spring-context.xml");
    /**
     * 查询
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String listProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //获取页码
        String pageNum = request.getParameter("pageNum");
        //获取也大小 每页显示条数
        String pageSize = request.getParameter("pageSize");
        //校验
        int page_num = 1; //默认从第一页开始
        int page_size = 8;//默认每页显示8条数据
        if (!StringUtil.isEmpty(pageNum)) {//如果前端给我们页码
            page_num = Integer.parseInt(pageNum);
            if (page_num < 0) {
                page_num = 1;
            }
        }
        if (!StringUtil.isEmpty(pageSize)) {//如果前端给我们页码
            page_size = Integer.parseInt(pageSize);
            if (page_size < 0) {
                page_size = 8;
            }
        }
        List<Object> params = new ArrayList<>();
        //调用业务逻辑
        try {
            ProfileService profileService = new ProfileServiceImpl();
            List<Profile> profiles = profileService.selectAll(page_num,page_size);
            PageInfo<Profile> profilePageInfo = new PageInfo<>(profiles);
            request.setAttribute("pageInfo",profilePageInfo);
            request.setAttribute("profiles",profiles);
            return "/list.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error","查询失败"+e.getMessage());
            return "/error.jsp";
        }
    }
    /**
     * 查询明细
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String detailProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //获取前端数据
        String id = request.getParameter("id");
        System.out.println(id+"          11111");
        //调用业务逻辑
        try {
            ProfileService bean = applicationContext.getBean(ProfileService.class);
            Profile profile = bean.selectById(Integer.parseInt(id));
            request.setAttribute("profile",profile);
            System.out.println(profile);
            return "/detail.jsp";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("error","查询失败"+e.getMessage());
            return "/error.jsp";
        }
    }
    /**
     * 修改前查询
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
        public String loadUpdateInfoProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //获取前端数据
        String id = request.getParameter("id");
        //调用业务逻辑
        try {
            ProfileService profileService = applicationContext.getBean(ProfileService.class);
            Profile profile = profileService.selectById(Integer.parseInt(id));
            request.setAttribute("updateInfo",profile);
            return "/update.jsp";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("error","查询失败"+e.getMessage());
            return "/error.jsp";
        }
    }
    /**
     * 修改
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String updateProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        //获取前端数据
        String id = request.getParameter("id");
        System.out.println("id = " + id);
        String name = request.getParameter("name");
        System.out.println("name = " + name);
        String birthday = request.getParameter("birthday");
        String gender = request.getParameter("gender");
        String career = request.getParameter("career");
        String address = request.getParameter("address");
        String mobile = request.getParameter("mobile");
        Part picture = request.getPart("picture");
        System.out.println("picture = " + picture);
        //校验
        if (StringUtil.isEmpty(name)){
            request.setAttribute("error","用户名不能为空");
            return "/error.jsp";
        }
        if (StringUtil.isEmpty(birthday)){
            request.setAttribute("error","日期不能为空");
            return "/error.jsp";
        }
        if (StringUtil.isEmpty(gender)){
            request.setAttribute("error","性别不能为空");
            return "/error.jsp";
        }
        if (StringUtil.isEmpty(career)){
            request.setAttribute("error","职业不能为空");
            return "/error.jsp";
        }
        if (StringUtil.isEmpty(address)){
            request.setAttribute("error","地址不能为空");
            return "/error.jsp";
        }
        if (StringUtil.isEmpty(mobile)){
            request.setAttribute("error","电话不能为空");
            return "/error.jsp";
        }
        //处理图片
        String dis = picture.getHeader("Content-Disposition");
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length()-1);
        filename = filename.substring(filename.lastIndexOf("\\")+1);
        String uuidFFFilename = null;
        if (!filename.equals("")){
            String basePath = this.getServletContext().getRealPath("WEB-INF"+ File.separator+"images");
            File dir = new File(basePath);
            if (!dir.exists()){
                dir.mkdirs();
            }
            String ext = filename.substring(filename.lastIndexOf(".")+1);
            uuidFFFilename = UUID.randomUUID().toString().replace("-","");
            uuidFFFilename = uuidFFFilename+"."+ext;
            picture.write(basePath+File.separator+uuidFFFilename);
            picture.delete();
        }
        //调用业务逻辑
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Profile profile = new Profile(Integer.parseInt(id),name,sdf.parse(birthday),gender,career,address,mobile,uuidFFFilename);
            System.out.println("profile = " + profile);
            ProfileService bean = applicationContext.getBean(ProfileService.class);
            bean.update(profile);
            response.getWriter().write("<script>alert('修改成功');window.location='/profileservlet?method=listProfile'</script>");
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error","修改失败"+e.getMessage());
            return "/error.jsp";
        }
    }

}
